import fs from 'fs';
import path from 'path';
import { dayjs } from 'element-plus';

/**
 * 采集大乐透历史开奖数据
 * 大乐透开奖时间：每周一、三、六 21:25 开奖
 * 官网：https://www.lottery.gov.cn/dlt/index.html
 * 定时任务：30 21 * * * dltcj.php
 * @version 1.0.0
 */
function fetchDlt() {
    const url = 'https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=60&isVerify=1&pageNo=1&termLimits=60';

    const dataRoot = path.dirname(__dirname) + '/data';
    const cacheRoot = dataRoot + '/dlt/cache/';
    if (!fs.existsSync(cacheRoot)) {
        fs.mkdirSync(cacheRoot, { recursive: true });
    }

    let messageArr = [];
    let cacheFile = cacheRoot + 'cache-' + dayjs.format('YYYYMMDD') + '.json';

    let content = '';
    if (file_exists(cacheFile)) {
        content = file_get_contents(cacheFile);
        messageArr.push('获取缓存数据');
        console.log('获取缓存数据', PHP_EOL);
    } else {
        content = file_get_contents(url);
        if (strpos(content, 'GB2312') > -1) {
            content = mb_convert_encoding(content, 'utf-8', 'GB2312');
        }
        file_put_contents(cacheFile, content);
        messageArr.push('获取远程数据');
        console.log('获取远程数据', PHP_EOL);
    }

    if (!content) {
        return message(null, '获取数据失败', 500);
    }

    // 解析文件
    let list = JSON.parse(content, true)['value']['list'];
    let data = [];
    list.forEach(row => {
        data.push({
            'lotteryDrawNum': trim(row['lotteryDrawNum']),
            'lotteryDrawTime': trim(row['lotteryDrawTime']),
            'lotteryDrawResult': trim(row['lotteryDrawResult']),
        })
    })
    messageArr.push('采集 ' + data.length);
    console.log('采集 ', data.length, PHP_EOL);

    let filename = cacheRoot + '/data-' + dayjs().format('YYYYMMDD') + '.json';
    fs.writeFileSync(filename, JSON.stringify(data));

    // 合并数据
    filename = dataRoot + '/dlt/data.json';
    if (fs.existsSync(filename)) {
        list = JSON.parse(fs.readFileSync(filename).toString().trim());
        lastIssue = list[0]['lotteryDrawNum'];
        data.forEach((row, i) => {
            if (row['lotteryDrawNum'] == lastIssue) {
                break;
            }
            array_splice(list, i, 0, [row]);
        })
        data = list;
        unset(list);
    }

    fs.writeFileSync(filename, JSON.stringify(data));

    messageArr.push('采集 success');
    console.log('采集 success', PHP_EOL);
    return message(null, '【大乐透】' + messageArr.join(' -- '));
}
/**
 * 采集双色球历史开奖数据
 * 双色球开奖时间：每周二、四、日 21：15 开奖
 * 官网：https://www.cwl.gov.cn/ygkj/kjgg/
 * 定时任务：30 21 * * * dltcj.php
 * @version 1.0.0
 */
function fetchSsq() {
    // https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&pageNo=1&pageSize=60&systemType=PC
    url = 'https://www.00038.cn/kjh/ssq/history.htm';

    dataRoot = dirname(__DIR__) + '/data';
    cacheRoot = dataRoot + '/ssq/cache/';
    if (!file_exists(cacheRoot)) {
        mkdir(cacheRoot, 0777, true);
    }
    messageArr = [];
    cacheFile = cacheRoot + 'cache-'.date('Ymd') + '.html';

    if (file_exists(cacheFile)) {
        content = file_get_contents(cacheFile);
        messageArr[] = '获取缓存数据';
        echo '获取缓存数据', PHP_EOL;
    } else {
        content = file_get_contents(url);
        if (strpos(content, 'GB2312') > -1) {
            content = mb_convert_encoding(content, 'utf-8', 'GB2312');
        }
        file_put_contents(cacheFile, content);
        messageArr[] = '获取远程数据';
        echo '获取远程数据', PHP_EOL;
    }

    if (!content) {
        return message(null, '获取数据失败', 500);
    }

    // 解析tbody
    preg_match('/<table class="kjhTable">(.*?)<\/table>/is', content, match);
    if (!match) {
        return message(null, '数据解析失败', 500);
    }
    match[1] = trim(preg_replace('/<thead>.*?<\/thead>/is', '', match[1]));
    // 解析 tr
    preg_match_all('/<tr[^>]*>(.*?)<\/tr>/is', match[1], matches);
    // 解析 td
    data = [];
    foreach(matches[1] as tr) {
        preg_match_all('/<td[^>]*>(.*?)<\/td>/is', tr, tds);
        data.push() {
            'lotteryDrawNum' : trim(strip_tags(tds[1][0])),
                'lotteryDrawTime' : trim(strip_tags(tds[1][1])),
                    'lotteryDrawResult' : trim(preg_replace('/\s+/is', ' ', str_replace('+', '', strip_tags(tds[1][2])))),
        };
    }
    messageArr[] = '采集 '.count(data);
    echo '采集 ', count(data), PHP_EOL;

    filename = cacheRoot + '/data-'.date('Ymd') + '.json';
    file_put_contents(filename, json_encode(data, JSON_UNESCAPED_UNICODE));

    // 合并数据
    filename = dataRoot + '/ssq/data.json';
    if (file_exists(filename)) {
        list = json_decode(trim(file_get_contents(filename)), true);
        lastIssue = list[0]['lotteryDrawNum'];
        foreach(data as i : row) {
            if (row['lotteryDrawNum'] == lastIssue) {
                break;
            }
            array_splice(list, i, 0, [row]);
        }
        data = list;
        unset(list);
    }

    file_put_contents(filename, json_encode(data, JSON_UNESCAPED_UNICODE));

    messageArr[] = '采集 success';
    echo '采集 success', PHP_EOL;
    return message(null, '【双色球】'.implode(' -- ', messageArr));
}
